using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
using UnityEngine;

public class SelfNetwork
{
		private const int buffSize = 20 * 1024;
		private Socket socket;
		private int nowPktLength = -1;
		private int nowReadIndex = 0;
		private int nowWriteIndex = 0;
		private byte[] allReceiveByte = new byte[buffSize];
		private float heatTime;
		private Thread thd ;
		public SelfNetwork ()
		{
			
		}

		public void Destroy()
		{
			if (thd != null)
				thd.Abort ();
			if (socket != null) 
			{
				if(socket.Connected)
					socket.Close();
			}
		}
		
		public void HeatUpdate ()
		{
                //if (socket != null) {
                //        if ((Time.time - heatTime) > 60) {
                //                heatTime = Time.time;
                //                SendPacket (new HeatPacket ());
                //        }	
                //}
		}
	
		public void LinkGame (string ip, int port)
		{ 
				IPEndPoint epServer = new IPEndPoint (IPAddress.Parse (ip), port);
				socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				socket.NoDelay = true;
				socket.BeginConnect (epServer, new AsyncCallback (ConnectResult), socket);
		}

		private void ConnectResult (IAsyncResult rec_socket)
		{
            try
            {
                if (socket.Connected){
                    thd = new Thread(new ThreadStart(this.Work));
                    thd.Start();
                    Debug.Log("Connect");
                }
                else {
                    Debug.Log("Connect error");
                }
            }
            catch
            {

            }
		}

		public void Work ()
		{
            while (true)
            {
                //if (socket.Connected)
                //{
                //    ReceiveData();
                //}
                Thread.Sleep(10);
            }
		}

		private void ReceiveData ()
		{
            //if (socket.Connected == false)
            //    return;
            //    byte[] bt = new byte[buffSize];
            //    int leng = socket.Receive (bt, bt.Length, SocketFlags.None);
            //    if (leng > buffSize - nowWriteIndex) {
            //            byte[] newReceiveByte = new byte[buffSize];
            //            ByteCode.copyByte (allReceiveByte, nowReadIndex, newReceiveByte, 0, nowWriteIndex - nowReadIndex);
            //            allReceiveByte = newReceiveByte;
            //            nowWriteIndex = nowWriteIndex - nowReadIndex;
            //            nowReadIndex = 0;
            //    }
            //    ByteCode.copyByte (bt, 0, allReceiveByte, nowWriteIndex, leng);
            //    bt = null;
            //    nowWriteIndex = nowWriteIndex + leng;
            //    DecodeData ();
		}
		
		private void DecodeData ()
		{
                //while (true) {
                //        if (nowPktLength == -1) {
                //                if (nowWriteIndex - nowReadIndex >= 4) {
                //                        byte[] B2 = new byte[4];
                //                        ByteCode.copyByte (allReceiveByte, nowReadIndex, B2, 0, 4);
                //                        nowReadIndex += 4;
                //                        nowPktLength = ByteCode.getInt (B2, 0);
                //                } else {
                //                        break;
                //                }
                //        }
			
                //        if (nowPktLength != -1) {
                //                if (nowWriteIndex - nowReadIndex >= nowPktLength) {
                //                        byte[] needReadBytes = new byte[nowPktLength];
                //                        ByteCode.copyByte (allReceiveByte, nowReadIndex, needReadBytes, 0, nowPktLength);
                //                        nowReadIndex += nowPktLength;
                //                        nowPktLength = -1;
                //                        Deserializer deser = new Deserializer ();
                //                        deser.DeserializerData (needReadBytes);
                //                } else {
                //                        break;
                //                }
                //        }
                //}
		}

        //public void SendPacket (BasePacket pkt)
        //{
        //        if (socket==null||socket.Connected == false) {
        //                GameMain.instance.evt.CallEvent ((int)GameEventTypeDefine.NetError, null);
        //                Debug.Log ("network error");
        //                return;
        //        }
        //        Serializer des = new Serializer ();
        //        des.SendData (pkt, pkt.pktType);
        //        SendData (des.sendBuff, des.nowWriteIndex);
        //}

        public void SendData(byte[] bts)
        {
            socket.Send(bts);
        }
}

